/*
 * Copyright (c) 2025 lhjhit
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/kernel.h>

 #include <zephyr/logging/log.h>
#include <zephyr/device.h>
#include <zephyr/drivers/gpio.h>

#include "led.h"

LOG_MODULE_REGISTER(LED_MODULE, LOG_LEVEL_INF);

#define LED0_NODE	DT_ALIAS(led0)
#if !DT_NODE_HAS_STATUS_OKAY(LED0_NODE)
#error "Unsupported board: led0 devicetree alias is not defined"
#endif

static const struct gpio_dt_spec 	led_status = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
static struct k_work_delayable 	blink_work;
static bool	led_is_on;

void blink_timeout(struct k_work *work)
{
	led_is_on = !led_is_on;
	gpio_pin_set(led_status.port, led_status.pin, (int)led_is_on);

	k_work_schedule(&blink_work, BLINK_ONOFF);
}

int led_setup(void)
{
	int ret;

	if (!gpio_is_ready_dt(&led_status)) {
		LOG_ERR("led_status GPIO failed");
		return -EIO;
	}

	ret = gpio_pin_configure_dt(&led_status, GPIO_OUTPUT_ACTIVE);
	if (ret) {
        LOG_ERR("led_status GPIO configure failed: %d", ret);
		return -EIO;
	}

	k_work_init_delayable(&blink_work, blink_timeout);

	return 0;
}

void blink_start(void)
{
	led_is_on = false;
	gpio_pin_set(led_status.port, led_status.pin, (int)led_is_on);
	k_work_schedule(&blink_work, BLINK_ONOFF);
}

void blink_stop(void)
{
	struct k_work_sync work_sync;

	k_work_cancel_delayable_sync(&blink_work, &work_sync);

	led_is_on = false;
	gpio_pin_set(led_status.port, led_status.pin, (int)led_is_on);
}